package com.szh.zx.javacorecorret.chap1;

import java.util.concurrent.Semaphore;

public class TestAcquire {
	private Semaphore semaphore = new Semaphore(10);
	public void testMethod(){
		try {
			// 有参方法的功能是每次调用1次此方法，就使用x个许可
			semaphore.acquire(2);
			System.out.println(Thread.currentThread().getName()+"：begin time:"+System.currentTimeMillis());
			int sleepValue = ((int) (Math.random()*10000));
			System.out.println(Thread.currentThread().getName()+" 停止了 "+(sleepValue/1000)+"秒");

			System.out.println(Thread.currentThread().getName()+"：end time:"+System.currentTimeMillis());
			semaphore.release(2);
		}catch (InterruptedException e){
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		TestAcquire testAcquire = new TestAcquire();
		ThreadD[] a = new ThreadD[10];
		for (int i = 0; i < 10; i++) {
			a[i]=new ThreadD(testAcquire);
			a[i].start();
		}

	}
}
class ThreadD extends Thread{
	private TestAcquire service;

	public ThreadD(TestAcquire service) {
		super();
		this.service = service;
	}

	@Override
	public void run() {
		service.testMethod();
	}
}